package handler

import (
	"awesomeProject/util"
	"strconv"

	"github.com/gin-gonic/gin"

	"awesomeProject/app/model"
	"awesomeProject/app/request"
	"awesomeProject/app/response"
	"awesomeProject/app/service"
	"awesomeProject/app/verify"
)

type PermissionHandler struct{}

var permissionSrv service.PermissionSrv

// Pagination 分页列表
func (r PermissionHandler) Pagination(ctx *gin.Context) {
	var req request.PermissionPagination
	_ = ctx.Bind(&req)
	if err := verify.PermissionPagination(&req); err != nil {
		response.Result(ctx, response.ErrInvalidParam.SetMsg(err.Error()))
		return
	}

	response.Result(ctx, permissionSrv.Pagination(req))
	return
}

// Create 创建
func (r PermissionHandler) Create(ctx *gin.Context) {
	var req request.PermissionCreate
	_ = ctx.Bind(&req)

	// 表单校验
	if err := verify.PermissionCreate(&req); err != nil {
		response.Result(ctx, response.ErrInvalidParam.SetMsg(err.Error()))
		return
	}

	uid := util.CurrentLoginUid(ctx)
	// 执行创建
	response.Result(ctx, permissionSrv.Create(model.PermissionFillAble{
		Uri:       req.Uri,
		Method:    req.Method,
		Name:      req.Name,
		Desc:      req.Desc,
		CreatedBy: uid,
		UpdatedBy: uid,
		Group:     req.Group,
		Super:     req.Super,
	}))
	return
}

// Update 更新
func (r PermissionHandler) Update(ctx *gin.Context) {
	id := ctx.Param("id")
	idInt, _ := strconv.Atoi(id)
	var req request.PermissionUpdate
	_ = ctx.Bind(&req)
	if err := verify.PermissionUpdate(&req); err != nil {
		response.Result(ctx, response.ErrInvalidParam.SetMsg(err.Error()))
		return
	}

	response.Result(ctx, permissionSrv.Update(uint(idInt), req))
	return
}

// All 所有权限
func (r *PermissionHandler) All(ctx *gin.Context) {
	user, _ := ctx.Get("user")
	response.Result(ctx, permissionSrv.All(user.(model.User).SuperAdmin))
	return
}

// Show 查看
func (r *PermissionHandler) Show(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Param("id"))
	response.Result(ctx, permissionSrv.Show(uint(id)))
	return
}

// Del 删除
func (r *PermissionHandler) Del(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Param("id"))
	response.Result(ctx, permissionSrv.Del(uint(id)))
	return
}

// Destroy 软删除
func (r PermissionHandler) Destroy(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Param("id"))
	response.Result(ctx, permissionSrv.Destroy(uint(id)))
	return
}

func (r *PermissionHandler) Groups(ctx *gin.Context) {
	response.Result(ctx, permissionSrv.Groups())
	return
}
